﻿// Members.Model.cs
//

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using BookClub.Core;
using BookClub.Web.Services;
using BookClub.Web.DataModel;

namespace BookClub.Pages {

    public class MembersModel : ViewModelBase {

        private MembersContext _membersContext;
        private ObservableCollection<Member> _members;

        private Member _newMember;

        public MembersModel() {
            _membersContext = new MembersContext();
            _membersContext.Load(_membersContext.GetMembersQuery(), delegate(LoadOperation<Member> loadOperation) {
                if (loadOperation.HasError == false) {
                    UpdateMembers();
                }
                else {
                    MessageBox.Show("There was an error loading the list of members.");
                    loadOperation.MarkErrorAsHandled();
                }
            }, null);
        }

        public IEnumerable<Member> Members {
            get {
                return _members;
            }
        }

        public Member NewMember {
            get {
                if (_newMember == null) {
                    _newMember = new Member();
                }
                return _newMember;
            }
        }

        public void AddMember() {
            if (_newMember.Validate(_membersContext.ValidationContext) == false) {
                return;
            }

            _membersContext.Members.Add(_newMember);
            _membersContext.SubmitChanges(delegate(SubmitOperation operation) {
                if (operation.HasError) {
                    MessageBox.Show("There was an error saving the new member.");
                    _membersContext.Members.Remove(_newMember);
                }
                else {
                    _newMember = null;
                    UpdateMembers();
                }
            }, null);
        }

        public void CancelAddMember() {
            _newMember = null;
            RaisePropertyChanged("NewMember");
        }

        private void UpdateMembers() {
            _members = new ObservableCollection<Member>(_membersContext.Members.OrderBy(m => m.MemberName));
            RaisePropertyChanged("Members");
        }
    }
}
